//
//  ORRegisteredViewController.m
//  News
//
//  Created by rimi on 2016/12/9.
//  Copyright © 2016年 dongfumei. All rights reserved.
//

#import "ORRegisteredViewController.h"
#import "ORUserTextField.h"
#import "ORLoginsViewController.h"

@interface ORRegisteredViewController ()

//账户$$密码&&确认密码&&邮箱
@property (nonatomic, strong)ORUserTextField *account;
@property (nonatomic, strong)ORUserTextField *passWord;
@property (nonatomic, strong)ORUserTextField *confirmPass;
@property (nonatomic, strong)ORUserTextField *emailTextField;
//确定注册
@property (nonatomic, strong)UIButton *confirmRegistered;
//关闭
@property (nonatomic, strong) UIButton *ShutButton;

@end

@implementation ORRegisteredViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
    
}

- (void)initUI{
    
    [self.view addSubview:self.account];
    [self.view addSubview:self.passWord];
    [self.view addSubview:self.confirmPass];
    [self.view addSubview:self.confirmRegistered];
    [self.view addSubview:self.emailTextField];
    [self.view addSubview:self.ShutButton];
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    // 键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}

-(void)keyBoardWillShow:(NSNotification *)notifcation{
    CGFloat maxY;
    if (self.emailTextField.isFirstResponder) {
        maxY = CGRectGetMaxY(self.emailTextField.frame);
    }else{
        maxY = CGRectGetMaxY(self.ShutButton.frame);
    }
    CGRect keyBoardFrame = [notifcation.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
    CGFloat screeH = [UIScreen mainScreen].bounds.size.height;
    CGFloat space = screeH - keyBoardFrame.size.height - maxY;
    if (space > 0) {
        return;
    }else{
        CGFloat duration = [notifcation.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        [UIView animateWithDuration:duration animations:^{
            CGRect bounds = self.view.bounds;
            bounds.origin.y -= space -40;
            self.view.bounds = bounds;
        }];
    }
}

-(void)keyBoardWillHide:(NSNotification *)notifcation{
    CGFloat duration = [notifcation.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        
        CGRect bounds = self.view.bounds;
        bounds.origin.y = 0;
        self.view.bounds = bounds;
        
    }];
}

- (void)alertWithTitle:(NSString *)title Message:(NSString *)message buttonBlock:(void(^)(void))block {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (block) {
            block();
        }
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark - Button

- (void)confirmRegisteredEvent{
    
    NSString *username = self.account.text;
    NSString *password = self.confirmPass.text;
    NSString *email = self.emailTextField.text;
    
    if ((self.account.text.length == 0 || self.passWord.text.length == 0 || self.confirmPass.text.length == 0)) {
        
        [self alertWithTitle:@"" Message:@"您输入的账号或者密码为空!" buttonBlock:nil];
        return;
    }else{
        
        if ((self.account.text.length <= 18 && self.account.text.length >= 6) &&  (self.passWord.text.length <= 18 && self.passWord.text.length >= 6) ) {
            
            if ([self.passWord.text isEqualToString:self.confirmPass.text]) {
                
                // LeanCloud - 注册
                // https://leancloud.cn/docs/leanstorage_guide-objc.html#用户名和密码注册
                AVUser *user = [AVUser user];
                user.username = username;
                user.password = password;
                user.email = email;
                //设置默认头像
                AVFile *file = [AVFile fileWithData:UIImageJPEGRepresentation([UIImage imageNamed:@"默认头像"], 0.5)];
                
                NSString *name = self.account.text;
                NSString *sex = @"男";
                [user setObject:name forKey:@"name"];
                [user setObject:sex forKey:@"sex"];
                [user setObject:file forKey:@"headImage"];
                [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                    if (error) {
                        
                        [self alertWithTitle:@"" Message:@"网络出现一点点问题！修改失败！" buttonBlock:nil];
                        
                        return ;
                    }
                }];
                
                __weak typeof (self) welkSelf = self;
                [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                        [self alertWithTitle:@"" Message:@"注册成功！要去邮箱验证才能登录哦！" buttonBlock:^{
                            [welkSelf dismissViewControllerAnimated:YES completion:nil];
                        }];
                        
                        
                        
                    } else {
                        
                        NSInteger code = error.code;
                        
                        if (code == 125) {
                            [self alertWithTitle:@"" Message:@"邮箱不正确" buttonBlock:nil];
                        } else if (code == 203) {
                            [self alertWithTitle:@"" Message:@"此电子邮箱已经被占用" buttonBlock:nil];
                        } else if (code == 202) {
                            [self alertWithTitle:@"" Message:@"用户名已被占用" buttonBlock:nil];
                        } else {
                            [self alertWithTitle:@"" Message:@"注册失败" buttonBlock:nil];
                        }
                    }
                }];
                
            }
        }else{
            [self alertWithTitle:@"温馨提示" Message:@"请输入6~18位数的账号或密码" buttonBlock:nil];
        }
    }
}

- (void)shutSele{
    
    [self dismissViewControllerAnimated:NO completion:nil];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

#pragma mark - getter

- (ORUserTextField *)account{
    if (!_account) {
        _account = [[ORUserTextField alloc]initWithFrame:AAdaptionRect(0, 0, 300, 44) WithIconName:@"" WithPlaceholder:@"请输入注册账号"];
        _account.center = AAadaptationPoint(kBaseWidth/2, 200/AAdaptationWidth());
        _account.clearButtonMode = UITextFieldViewModeWhileEditing;
    }
    return _account;
}

- (ORUserTextField *)passWord{
    if (!_passWord) {
        _passWord = [[ORUserTextField alloc]initWithFrame:AAdaptionRect(0, 0, 300, 44) WithIconName:@"" WithPlaceholder:@"请输入注册密码"];
        _passWord.center = AAadaptationPoint(kBaseWidth/2, CGRectGetMaxY(self.account.frame)/AAdaptationWidth()+30);
        _passWord.clearButtonMode = UITextFieldViewModeWhileEditing;
    }
    return _passWord;
}

- (ORUserTextField *)confirmPass{
    if (!_confirmPass) {
        _confirmPass = [[ORUserTextField alloc]initWithFrame:AAdaptionRect(0, 0, 300, 44) WithIconName:@"" WithPlaceholder:@"请确认注册密码"];
        _confirmPass.center = AAadaptationPoint(kBaseWidth/2, CGRectGetMaxY(self.passWord.frame)/AAdaptationWidth()+30);
        _confirmPass.clearButtonMode = UITextFieldViewModeWhileEditing;
    }
    return _confirmPass;
}

- (ORUserTextField *)emailTextField{
    if (!_emailTextField) {
        _emailTextField = [[ORUserTextField alloc]initWithFrame:AAdaptionRect(0, 0, 300, 44) WithIconName:@"" WithPlaceholder:@"请输入注册邮箱"];
        _emailTextField.center = AAadaptationPoint(kBaseWidth/2, CGRectGetMaxY(self.confirmPass.frame)/AAdaptationWidth()+30);
        _emailTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    }
    return _emailTextField;
}

- (UIButton *)confirmRegistered{
    if (!_confirmRegistered) {
        _confirmRegistered = [[UIButton alloc]initWithFrame:AAdaptionRect(0, 0, 280, 44)];
        _confirmRegistered.center = AAadaptationPoint(kBaseWidth/2, CGRectGetMaxY(self.emailTextField.frame)/AAdaptationWidth()+44);
        [_confirmRegistered setTitle:@"确定注册" forState:UIControlStateNormal];
        [_confirmRegistered addTarget:self action:@selector(confirmRegisteredEvent) forControlEvents:UIControlEventTouchUpInside];
        _confirmRegistered.layer.cornerRadius = 3;
        _confirmRegistered.backgroundColor = MainColor;
    }
    return _confirmRegistered;
}

- (UIButton *)ShutButton{
    if (!_ShutButton) {
        _ShutButton = [[UIButton alloc]initWithFrame:AAdaptionRect(30, 30, 30, 30)];
        [_ShutButton setImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
        [_ShutButton addTarget:self action:@selector(shutSele) forControlEvents:UIControlEventTouchUpInside];
    }
    return _ShutButton;
}

@end
